package com.eascs.banknet.log.service;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.banknet.boc.dao.LoanapplyDao;
import com.eascs.banknet.common.entity.LoanapplyEntity;
import com.eascs.banknet.log.dao.LogDao;
import com.eascs.banknet.log.entity.LogEntity;
import com.eascs.common.util.StringUtil;

@Service
public class LogService {
	private static final Logger logger = LoggerFactory.getLogger(LogService.class);

	@Autowired
	private LogDao logDao;

	@Autowired
	private LoanapplyDao loanapplyDao;

	public void writeLog(LogEntity logEntity, String appno, int resultType, String resultDesc) {
		try {
			LogEntity saveEntity = logEntity;
			if (StringUtil.hasText(appno)) {
				// 002状态更新
				if (StringUtils.equalsIgnoreCase(logEntity.getTransType(), "002")) {
					LogEntity queryLog = logDao.getEntityByAppNoAndTransType(appno, logEntity.getTransType());
					if (queryLog != null) {
						// 存在则更新
						queryLog.setEndTime(new Date());
						queryLog.setResultDesc(resultDesc);
						logDao.updateById(queryLog);
						return;
					}
				}

				LoanapplyEntity loanapplyEntity = loanapplyDao.getLoanEntityNoByAppno(appno);
				if (null != loanapplyEntity) {
					saveEntity.setLoanapplyNo(loanapplyEntity.getLoanapplyNo());
					saveEntity.setBillCode(loanapplyEntity.getBillCode());
				}
				saveEntity.setAppNo(appno);
				saveEntity.setResultType(resultType);
				saveEntity.setResultDesc(resultDesc);
				saveEntity.setEndTime(new Date());
				logger.info("保存日志信息:[{}]", saveEntity.toString());
				logDao.insert(saveEntity);
			}
		} catch (Exception e) {
			logger.error("保存日志信息异常:[{}]", e.getMessage());
			e.printStackTrace();
		}
	}

	public void writeB01Log(LogEntity logEntity, String appno, String loanapplyNo, String billCode, int resultType,
			String resultDesc) {
		try {
			LogEntity saveEntity = logEntity;
			saveEntity.setAppNo(appno);
			saveEntity.setLoanapplyNo(loanapplyNo);
			saveEntity.setBillCode(billCode);
			saveEntity.setResultType(resultType);
			saveEntity.setResultDesc(resultDesc);
			saveEntity.setEndTime(new Date());
			logger.info("保存日志信息:[{}]", saveEntity.toString());
			logDao.insert(saveEntity);
		} catch (Exception e) {
			logger.error("保存日志信息异常:[{}]", e.getMessage());
			e.printStackTrace();
		}
	}
}
